/**
 * Created by Thyiad on 2017/11/13.
 */
import axios from 'axios';
import { Message, MessageBox } from 'element-ui'
import auth from './auth';
import Cookies from 'js-cookie';
import store from '@/store'
import * as api from '../constants/api';
import * as actionTypes from '../constants/action-types';
import * as mutationTypes from '../constants/mutation-types';

const service = axios.create({
  // baseURL: process.env.BASE_API,     // 可以在config/env.js中设置不同环境下访问的 api host
  baseURL: api.HOST,
  timeout: 100000
})

service.interceptors.request.use(config => {
  let token = auth.getToken();
  if (token) {
    config.headers['X-Token'] = token
  }
  return config
}, error => {
  console.log(error)
  Promise.reject(error)
})

service.interceptors.response.use(
  response=>response.data,
  // response => {
  //   const res = response.data;
  //   if (res.code !== 20000) {
  //     Message({
  //       message: res.message,
  //       type: 'error',
  //       duration: 5 * 1000
  //     });
  //     // 50008:非法的token; 50012:其他客户端登录了;  50014:Token 过期了;
  //     if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
  //       MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出', {
  //         confirmButtonText: '重新登录',
  //         cancelButtonText: '取消',
  //         type: 'warning'
  //       }).then(() => {
  //         store.dispatch(actionTypes.LOGOUT).then(() => {
  //           location.reload();// 为了重新实例化vue-router对象 避免bug
  //         });
  //       })
  //     }
  //     return Promise.reject('error');
  //   } else {
  //     return response.data.data;
  //   }
  // },
  error => {
    console.log('err' + error)// for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

let Util = {
  cache(key, val) {
    if (key === 'clear') {
      window.localStorage.clear();
    } else if (val === null) {
      window.localStorage.removeItem(key);
    } else if (val) {
      window.localStorage[key] = val;
    } else {
      return window.localStorage[key];
    }
  },
  cacheSession(key, val) {
    if (key === 'clear') {
      window.sessionStorage.clear();
    } else if (val === null) {
      window.sessionStorage.removeItem(key);
    } else if (val) {
      window.sessionStorage[key] = val;
    } else {
      return window.sessionStorage[key];
    }
  },
  cookie(key, val){
    if(val===null){
      Cookies.remove(key);
    }else if(val){
      Cookies.set(key,val);
    }else{
      return Cookies.get(key);
    }
  },
  post: function(url, data){
    return service({
      url: url,
      method: 'post',
      data,
    })
  }
}

export default Util;
